<template>
  <common-list>
    <!-- 上-->
    <common-search slot="search" @search="handleQuery" @reset="resetQuery">
      <el-form
        :inline="true"
        ref="queryParams"
        label-width="75px"
        @submit.native.prevent
      >
        <el-form-item label="告警类型" prop="alarmType">
          <el-select
            v-model="queryParams.alarmType"
            filterable
            clearable
            style="width: 100%"
          >
            <el-option label="全部" :value="null"></el-option>
            <el-option
              v-for="(item, index) in alarmTypeOption"
              :key="index"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="告警子类型" prop="alarmBusiness">
          <common-input
            clearable
            @enter="handleQuery"
            v-model="queryParams.alarmBusiness"
          />
        </el-form-item> -->
      </el-form>
    </common-search>
    <!-- 中 （三个按钮）-->
    <div slot="tools">
      <el-button
        type="primary"
        plain
        icon="el-icon-plus"
        @click="handleAdd"
        v-hasPermi="['config:alarmbusiness:add']"
        >新增</el-button
      >
      <el-button
        type="danger"
        plain
        icon="el-icon-delete"
        @click="handleDelete()"
        :disabled="!showBatch"
        v-hasPermi="['config:alarmbusiness:remove']"
        >批量删除</el-button
      >
    </div>
    <!--  下 -->
    <common-table
      slot="content"
      :data="list"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="告警类型" align="left" prop="alarmType">
        <template slot-scope="scope">
          {{ getAlarmTypeNameById(scope.row.alarmType) }}
        </template>
      </el-table-column>
      <!-- <el-table-column label="告警子类型" align="left" prop="alarmBusiness" /> -->
      <el-table-column label="操作" align="left" width="90">
        <template slot-scope="scope">
          <el-button
            type="text"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['config:alarmbusiness:edit']"
            >编辑
          </el-button>
          <el-button
            type="text"
            @click="handleDelete(scope.row)"
            v-hasPermi="['config:alarmbusiness:remove']"
            >删除
          </el-button>
        </template>
      </el-table-column>
    </common-table>
    <pagination
      slot="pagination"
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <common-edit-dialog
      :title="isEdit ? '编辑告警业务' : '新增告警业务'"
      :visible="dialogShow"
      :button-loading="buttonLoading"
      @cancel="cancel"
      @submit="submitForm"
    >
      <el-form
        label-width="90px"
        :rules="rules"
        ref="form"
        :model="form"
        @submit.native.prevent
      >
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="告警类型" prop="alarmType">
              <el-select v-model="form.alarmType" filterable
                         clearable style="width: 100%">
                <el-option
                  v-for="(item, index) in alarmTypeOption"
                  :key="index"
                  :label="item.name"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12">
            <el-form-item label="告警子类型" prop="alarmBusiness">
              <common-input clearable v-model="form.alarmBusiness" />
            </el-form-item>
          </el-col> -->
        </el-row>
      </el-form>
    </common-edit-dialog>
  </common-list>
</template>

<script>
import {
  businessAdd,
  businessEdit,
  businessInfo,
  businessList,
  businessRemove,
  deleteForCheck,
} from "@/api/system/alarmbusiness";
import { alarmCodeGetAlarmType } from "@/api/system/alarmCode";
import BaseList from "@/mixins/BaseList";
export default {
  name: "index",
  mixins: [BaseList],
  data() {
    return {
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      alarmTypeOption: [],
      list: [],
      total: 0,
      isEdit: false,
      dialogShow: false,
      loading: false,
      rules: {
        alarmBusiness: [
          {
            required: true,
            message: "请输入告警子类型",
            trigger: "blur",
          },
        ],
        alarmType: [
          {
            required: true,
            message: "请选择告警类型",
            trigger: "blur",
          },
        ],
      },
      buttonLoading: false,
      form: {
        id: "",
        alarmBusiness: "",
        alarmType: "",
      },
      isDisabled: false,
    };
  },
  mounted() {
    this.getAlarmType();
  },
  methods: {
    reset() {
      this.form = {
        alarmBusiness: "",
        alarmType: "",
      };
    },

    getAlarmType() {
      alarmCodeGetAlarmType()
        .then((res) => {
          if (res && res.code === 200) {
            this.alarmTypeOption = res.data;
          } else {
            this.alarmTypeOption = [];
          }
        })
        .finally(() => {
          this.getList();
        });
    },

    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    resetQuery() {
      this.queryParams = this.$options.data().queryParams;
    },

    handleUpdate(row) {
      this.isEdit = true;
      this.dialogShow = true;
      Reflect.ownKeys(this.form).forEach((k) => (this.form[k] = row[k]));
      this.form.id = row.id;
      this.form.alarmType = this.alarmTypeOption.find(
        (item) => +item.id === row.alarmType
      ).id;
    },
    handleAdd() {
      this.reset();
      this.isEdit = false;
      this.dialogShow = true;
    },

    getList() {
      this.loading = true;
      businessList(this.queryParams)
        .then((res) => {
          if (res && res.code === 200) {
            this.total = res.total;
            this.list = res.rows;
          } else {
            this.list = [];
            this.total = 0;
            this.handleListTips(res);
          }
        })
        .finally(() => {
          this.loading = false;
        });
    },
    getAlarmTypeNameById(id) {
      let at = this.alarmTypeOption.find(
        (item) => parseInt(item.id) === parseInt(id)
      );
      return at ? at.name : "";
    },
    cancel() {
      this.dialogShow = false;
    },
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.buttonLoading = true;
          if (this.isEdit) {
            businessEdit(this.form)
              .then((res) => {
                if (res && res.code === 200) {
                  this.$GlobalSuccessMessage("编辑成功");
                  this.dialogShow = false;
                  this.getList();
                } else {
                  this.$GlobalErrorConfirm("编辑失败", res.msg);
                }
              })
              .finally(() => {
                this.buttonLoading = false;
              });
          } else {
            businessAdd(this.form)
              .then((res) => {
                if (res && res.code === 200) {
                  this.$GlobalSuccessMessage("新增成功");
                  this.dialogShow = false;
                  this.getList();
                } else {
                  this.$GlobalErrorConfirm("新增失败", res.msg);
                }
              })
              .finally(() => {
                this.buttonLoading = false;
              });
          }
        }
      });
    },
    deleteData(row) {
      const ids = row?.id || this.ids.join(",");
      this.$GlobalDeleteConfirm().then(() => {
        businessRemove({ ids }).then((res) => {
          if (res && res.code === 200) {
            this.$GlobalSuccessMessage("删除成功");
            if (
              this.queryParams.pageNum > 1 &&
              ids.split(",").length === this.list.length
            ) {
              this.queryParams.pageNum -= 1;
            }
            this.getList();
          } else {
            this.$GlobalErrorConfirm("删除失败", res.msg);
          }
        });
      }).catch(()=>{});
    },
    /**  删除前校验 */
    beforeDeleteForCheck(ids) {
      return new Promise((resolve, reject) => {
        deleteForCheck({ ids: ids })
          .then((res) => {
            if (res && res.code === 200) {
              resolve(res);
            } else {
              reject(res);
            }
          })
          .catch((err) => {
            reject(err);
          });
      });
    },
  },
};
</script>
